package com.frame.controller;

import cn.hutool.jwt.JWT;
import cn.hutool.jwt.JWTUtil;
import com.frame.domain.Leaves;
import com.frame.domain.SysDictData;
import com.frame.domain.SysUser;
import com.frame.domain.SysUserLeaves;
import com.frame.service.LeavesService;
import com.frame.service.SysUserService;
import com.frame.utils.Result;
import org.activiti.engine.HistoryService;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.history.HistoricProcessInstance;
import org.activiti.engine.repository.ProcessDefinition;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

@RestController
@RequestMapping("/leaves")
public class LeavesController {

    @Autowired
    private LeavesService leavesService;

    @Autowired
    private RepositoryService repositoryService;

    @Autowired
    private RuntimeService runtimeService;

    @Autowired
    private TaskService taskService;

    @Autowired
    private HistoryService historyService;

    @Autowired
    private HttpServletRequest request;

    @PostConstruct
    public Result deploy(){
        ProcessDefinition note = repositoryService.createProcessDefinitionQuery().processDefinitionKey("note").singleResult();
        if(note==null) {
            repositoryService.createDeployment().addClasspathResource("bpmn/note.bpmn20.xml").deploy();
        }
        else {
            System.out.println("流程已部署");
        }

        return Result.success();
    }

    @RequestMapping("/save")
    public Result save(@RequestBody Leaves leaves){
        boolean b=leavesService.save(leaves);
        if (b){
            HashMap<String, Object> map = new HashMap<>();
            map.put("name1",leaves.getName());
            map.put("name2",leaves.getBanzhang());
            map.put("name3",leaves.getDaoyuan());
            map.put("name4",leaves.getJiangshi());
            ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("note", leaves.getId() + "", map);
            if (processInstance!=null){
                return Result.success("请假申请成功");
            }else{
                return Result.success("请假申请失败");
            }
        }
        return Result.success("请假申请失败");
    }

    @RequestMapping("/list")
    public Result list(){
        Integer roleName = (Integer) JWTUtil.parseToken(request.getHeader("token")).getPayload("uid");
        List<Task> list = taskService.createTaskQuery().taskAssignee(roleName + "").list();
        ArrayList<Leaves> leavesArrayList = new ArrayList<>();
        for (Task task : list) {
            HistoricProcessInstance historicProcessInstance = historyService.createHistoricProcessInstanceQuery()
                    .processInstanceId(task.getProcessInstanceId())
                    .singleResult();
            String id = historicProcessInstance.getBusinessKey();
            Leaves leaves = leavesService.selectById(id);
            leaves.setTaskId(task.getId());
            leaves.setTaskName(task.getName());
            leavesService.updateLeaves(leaves);
            leavesArrayList.add(leaves);
        }
        return Result.success(leavesArrayList);
    }

    @Autowired
    SysUserService sysUserService;
    @RequestMapping("getName")
    public Result getName(){


        Integer UserId = (Integer) JWTUtil.parseToken(request.getHeader("token")).getPayload("uid");

        System.out.println(UserId);
        SysUser sysUser=sysUserService.selectUserById(UserId);
        return Result.success(sysUser.getUserName());
    }

    @RequestMapping("getLeaveType")
    public Result getLeaveType(){
        List<SysDictData> sysDictDataList=leavesService.getLeaveType();
        return Result.success(sysDictDataList);
    }

    @RequestMapping("getBanzhang")
    public Result getBanzhang(){
        List<SysUser> list=leavesService.getBanzhang();
        return Result.success(list);
    }

    @RequestMapping("getDaoyuan")
    public Result getDaoyuan(){
        List<SysUser> list=leavesService.getDaoyuan();
        return Result.success(list);
    }

    @RequestMapping("getJiangshi")
    public Result getJiangshi(){
        List<SysUser> list=leavesService.getJiangshi();
        return Result.success(list);
    }

    @RequestMapping("/getLeave")
    public Result getLeave(Integer id){
        Leaves leaves = leavesService.selectById(id+"");
        return Result.success(leaves);
    }

    @RequestMapping("shenpi")
    public Result shenpi(@RequestBody Leaves leaves){
        Leaves leaves1 = leavesService.selectById(leaves.getId() + "");
        leaves1.setContent(leaves.getContent());
        boolean b=leavesService.updateLeaves(leaves1);

        HashMap<String, Object> map = new HashMap<>();
        map.put("name2", leaves.getBanzhang()+"");
        map.put("name3", leaves.getJiangshi()+"");
        map.put("name4", leaves.getDaoyuan()+"");
        map.put("days",leaves1.getDays());
        taskService.complete(leaves1.getTaskId(),map);

        Integer UserId = (Integer) JWTUtil.parseToken(request.getHeader("token")).getPayload("uid");
        SysUserLeaves userLeave = new SysUserLeaves();
        userLeave.setUserId(UserId);
        userLeave.setLeavesId(leaves1.getId());
        userLeave.setReason(leaves.getContent());
        leavesService.insertUserLeaves(userLeave);
        return Result.success();
    }

    @RequestMapping("myCompletion")
    public Result myCompletion(){
        Integer UserId = (Integer) JWTUtil.parseToken(request.getHeader("token")).getPayload("uid");
        List<SysUserLeaves> list=leavesService.myCompletion(UserId);
        return Result.success(list);
    }

}
